package com.husd.framework.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author hushengdong@gome.com.cn
 * @date 2022/1/22 3:18 下午
 */
public class MmapExample {

    public static void main(String[] args) throws IOException, InterruptedException {

        String file = "/tmp/b.txt";
        long fileSize = 1024 * 1024 * 1;
        FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
//        fileChannel.position(fileChannel.size());
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, fileChannel.size(), fileSize);

        mappedByteBuffer.put("this is a test 2\n".getBytes(StandardCharsets.UTF_8));

        mappedByteBuffer.flip();
        System.out.println("before sleep");
        Thread.sleep(1000L * 10L);
        mappedByteBuffer.force();
        System.out.println("after sleep");

        fileChannel.close();
    }
}
